package bcs.icode.bridge;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class JavaBridge {
	static public Object get(Object obj, String name) {
		try {
			Class<?> cls = obj.getClass();
			String getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
			for (Method m : cls.getMethods()) {
				if (m.getName().equals(name)) {
					return new Function(name);
				} else if (m.getName().equals(getter) && m.getParameterTypes().length == 0) {
					return m.invoke(obj);
				}
			}
			
			for (Field f : cls.getFields()) {
				if (f.getName().equals(name)) {
					return f.get(obj);
				}
			}
		} catch (IllegalAccessException ex) {
			throw new RuntimeException(ex);
		} catch (InvocationTargetException ex) {
			throw new RuntimeException(ex);
		}
		throw new RuntimeException("Unknown field " + name);
	}
}
